package com.lebang.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lebang.component.RedisSdkClient;
import com.lebangweb.common.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

import java.util.Map;

import static com.lebang.controller.api.SdkUploadApi.ON_SDK_MEMBER;

/**
 * @Author: hwq
 * @Date: 2019/10/12 11:08
 * @Version 1.0
 */
@Component
@Slf4j
public class SdkReloadTask {

    @Autowired
    private RedisSdkClient sdkClient;
    public static final long HOUR = 1800000;
    public static final String SDK_QUEQUE = "SDK_QUEQUE";
    @Value("${info.is-cences}")
    private Boolean isStar;
    /**
     * 每30秒刷新一次奖励
     */
    //@Scheduled(cron = "0 0/5 * * * ?")
    @Scheduled(cron = "0/30 * * * * ?")
    public void execute() {
        if(!isStar){
            return;
        }
        long now = System.currentTimeMillis();
        if (sdkClient.tryGetDistributedLock("lock:Scheduled:SdkReloadTask", UUIDUtil.M(), 5000)) {
            log.debug("开始发送sdk");
            try  {
                Map<String, String> map = sdkClient.hgetall(ON_SDK_MEMBER);
                for (String v : map.values()) {
                    JSONObject jsonObject = JSON.parseObject(v);
                    Long time = jsonObject.getLongValue("time");
                    if (time != 0L) {
                        if (time + HOUR > now) {
                            sdkClient.lpush(SDK_QUEQUE, v);
                        } else {
                            sdkClient.hdel(ON_SDK_MEMBER, jsonObject.getString("memberId"));
                        }
                    }
                }
                log.debug("发送sdk人数:" + map.size() + "耗时:" + (System.currentTimeMillis() - now) + "毫秒");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            //其他系统执行
            log.debug("其他系统执行");
        }

    }
}
